#include "head.h"

int compareQsort(const void *a,const void *b){
    char **L = (char **)a;
    char **R = (char **)b;
    return strcasecmp(*L,*R);   // strcasecmp：比较时忽略大小写
}

int ls(const char *dirName,char *retArr){
    DIR *dirp = opendir(dirName);
    ERROR_CHECK(dirp,NULL,"opendir failed");

    int fileNum = 0;    // fileNum：目录流的目录/文件数目
    struct dirent *dirent_p = NULL;

    // 第一遍扫描：计算fileNum
    while((dirent_p = readdir(dirp)) != NULL){
       if(strcmp(dirent_p->d_name,".") == 0){
            continue;
        }

        else if(strcmp(dirent_p->d_name,"..") == 0){
            continue;
        }

        fileNum++;
    }

    rewinddir(dirp);    //倒带目录流指针
    
    char **fileArr = (char **)calloc(fileNum,sizeof(char *)); 
    ERROR_CHECK(fileArr,NULL,"calloc fileArr");
    for(int i = 0;i < fileNum;i++){
        fileArr[i] = (char *)calloc(256,sizeof(char));   //为每个字符串分配256个char大小的空间
    }

    // 第二遍扫描：将目录流中的目录/文件复制到字符串数组
    int idx = 0;    //字符串数组下一个插入位置
    while((dirent_p = readdir(dirp)) != NULL){
        if(strcmp(dirent_p->d_name,".") == 0){
            continue;
        }

        else if(strcmp(dirent_p->d_name,"..") == 0){
            continue;
        }

        memcpy(fileArr[idx++],dirent_p->d_name,strlen(dirent_p->d_name) + 1);
    }


    qsort(fileArr,fileNum,sizeof(char *),compareQsort);

    int cur = 0;
    memset(retArr,0,strlen(retArr));
    for(int i = 0;i < fileNum;i++){
        if((i != 0) && (i % 5) == 0){
            sprintf(retArr + cur,"\n");
            cur += 1;
        }
        int ret = sprintf(retArr + cur,"%-20s",fileArr[i]);
        cur += ret;

    }
    printf("------------\n%s\n",retArr);
    closedir(dirp);
    return 0;
}

#if 0
int main(){
    ls("../cloudStorage");
    return 0;
}
#endif

